const express = require('express')
const ReactSSR = require('react-dom/server')
const fs = require('fs')
const path = require('path')
const favicon = require('serve-favicon')

const serverRender = require('./util/server-render')

const isDev = process.env.NODE_ENV === "development"

const app = express();

const bodyParser = require('body-parser')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))

const session = require('express-session')
app.use(session({
  maxAge: 10 * 60 * 1000,
  name: 'sid',
  resave: false,
  saveUninitialized: false,
  secret: '(‘◇’)?'
}))

app.use(favicon(path.join(__dirname, '../favicon.ico')))

app.use('/api/user', require('./util/handler-login'))
app.use('/api', require('./util/proxy'))

if (!isDev) {
    const template = fs.readFileSync(path.join(__dirname, '../dist/server.ejs'), 'utf-8')
    const serverEntry = require('../dist/server-entry.js')
    app.use('/public', express.static(path.join(__dirname, '../dist')))
    app.get('*', function (req, res, next) {
        serverRender(serverEntry, template, req, res).catch(next)
    })
} else {
    const devStatic = require('./util/dev-static')
    devStatic(app)
}

app.use(function(error, req, res, next) {
  console.log(error)
  res.status(500).send(error)
})

app.listen(2333, function () {
   console.log('🚀 服务又又又起来了，正在监听2333端口(✌ﾟ∀ﾟ)☞')
});
